package org.mf.web.controller;

import java.util.List;

import org.mf.domain.User;
import org.mf.service.UserService;
import org.mf.web.pagination.Pager;
import org.mf.web.validation.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@SessionAttributes("user")
public class UsersController {
	private UserService userService;
	private UserValidator userValidator;

	@Autowired
	public UsersController(UserService userService, UserValidator userValidator) {
		this.userService = userService;
		this.userValidator = userValidator;
	}

	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public String index(Model model, Pager pager) {
		List l = userService.getPagedResults(pager).getResultSet();
		for (int i = 0; i < l.size(); i++) {
			System.out.println("***********************: "
					+ ((User) l.get(i)).getUsername());
		}
		model.addAttribute("users", userService.getPagedResults(pager));
		return "users/index";
	}

	@RequestMapping(value = "/users/add", method = RequestMethod.GET)
	public String add(Model model) {
		User user = new User();
		model.addAttribute("user", user);
		return "users/add";
	}

	@RequestMapping(value = "/users/add", method = RequestMethod.POST)
	public String create(Model model, @ModelAttribute("user") User user,
			BindingResult result, SessionStatus status) {
		userValidator.validate(user, result);
		if (result.hasErrors()) {
			model.addAttribute("user", user);
			return "users/add";
		} else {
			userService.save(user);
			return "redirect:/users";
		}
	}
}
